
import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import { deepEqual } from '../../../utils/objects';
import * as compDiviService from '../../../services/AccountDivi';

const daoName = "CompClieQylxWh";
const ButtonGroup = Button.Group;
const columns = [
  //{ title: '企业类型', width: 100, sorter: true, dataIndex: 'QYLXCaption', key: 'QYLX', dispaly: true },
  { title: '企业规模', width: 100, sorter: true, dataIndex: 'GJLXCaption', key: 'GJLX', dispaly: true },
];
const controls = [
  // { 
  //     name: "QYLX", label: "企业类型", type: "select", grid: 12 / 24, 
  //     data: [{ value: '1', label: '非中小' }, { value: '2', label: '中型' },
  //           { value: '3', label: '小型' }, { value: '4', label: '微型' }], 
  //     required: true 
  // },
  { 
      name: "GJLX", label: "企业规模", type: "select", grid: 12 / 24, 
      data: [{ value: '1', label: '大型' }, { value: '2', label: '中型' },
            { value: '3', label: '小型' }, { value: '4', label: '微型' }], 
      required: true 
  },
]
const EditFrom = dataEditCreate(daoName);
class CompClieQylxWhForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      searchData: {},
      diviDataSource: [],
      title: "",
      showEdit: false,
      isOK: 0
    };
  }
  componentWillReceiveProps(nextProps) {
    if ((!deepEqual(nextProps.jlid, this.props.jlid))) {
      this.loadData(nextProps.jlid)
    }
  }
  componentDidMount() {
    this.loadData(this.props.jlid)
  }
  loadData(jlid) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
      FieldName: "JLID",
      Operator: "=",
      FieldValues: '' + jlid
    })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    this.state.diviDataSource = [];
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks }
    });
  }
  searchHandle(data) {
    this.state.searchData = data
  }
  hideEditHandler() {
    this.props.dispatch({
      type: `${this.props.parentModel}/hideEdit`
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.setState({ diviDataSource: [] });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  diviDel() {
    let diviDsource = this.state.diviDataSource;
    if (diviDsource.length <= 0) {
      diviDsource = this.props.list;
    }
    diviDsource.splice(0, 1)
    let keys = this.refs.table.getSelectedRowKeys();
    keys.sort();
    if (keys.length <= 0) {
      message.info('请选择删除的数据行！');
      return
    }
    this.setState({ diviDataSource: diviDsource })
  }
  diviSubmit() {
    const datas = this.refs.table.state.datas;
    if(datas.length===0){
      message.info('请添加企业类型国标和行标！');
      return
    }
    let jlid = this.props.jlid;
    let dataSource = []
    datas.map(d => {
      let data = {
        JLID: jlid,
        QYLX: Number(d.QYLX),
        GJLX: Number(d.GJLX)
      }
      dataSource.push(data);
    })
    Modal.confirm({
      title: '提示',
      content: `请确认企业规模？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        compDiviService.ALterSaveCompClieQylx({ jlid,dataSource }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('企业规模维护成功！')
          } else {
            return;
          }
        }).catch(function (ex) {
          console.log('请求出错', ex)
        });
        let daoName = "CM_CORP_CUST_DIM"
        this.props.dispatch({
          type: `${daoName}/fetch`,
          payload: { daoName, page: 1, pageSize: 20 }
        });
      }
    });
  };
  DiviAdd() {
    let list = this.props
    if (list.list.length != 0) {
      message.info('请先清除现有企业规模');
      return;
    }
    const form = this.refs.diviForm.getForm();
    let isOK = true;
    let data = {};//空对象
    form.validateFields((err, values) => {
      if (!err) {
        if ((values.GJLX === undefined || values.GJLX === '')) {
          message.info('请选择企业规模！');
          isOK = false;
        } else {
            let QYLXCaption='';
            let GJLXCaption ='';
            data.QYLX = Number(values.QYLX);
            data.GJLX = Number(values.GJLX);
            if(data.QYLX===1)
                QYLXCaption='非中小';
            else if (data.QYLX===2)
                QYLXCaption='中型';
            else if (data.QYLX===3)
                QYLXCaption='小型';
            else if (data.QYLX===4)
                QYLXCaption='微型';
            if(data.GJLX===1)
                GJLXCaption='大型';
            else if (data.GJLX===2)
                GJLXCaption='中型';
            else if (data.GJLX===3)
                GJLXCaption='小型';
            else if (data.GJLX===4)
                GJLXCaption='微型';
            data.QYLXCaption =QYLXCaption;
            data.GJLXCaption=GJLXCaption;
        }
      }
    });
    if (!isOK) {
      return;
    }
    let QYLX=0
    let diviDs = this.state.diviDataSource
    diviDs.map(d => QYLX = d.QYLX)
    if (QYLX != 0) {
      message.info('企业规模已维护，请先删除现有企业规模');
      return;
    } else {
      diviDs.push(data);
      this.setState({ diviDataSource: diviDs });
    }
  }
  render() {
    let { list } = this.props
    list = this.state.diviDataSource.length <= 0 ? list : this.state.diviDataSource;
    const controlsFilter = [
      // {
      //   name: "QYLX", label: "企业类型", type: "select", grid: 6 / 24, required: false,
      //   dataType: "number", data: [{ value: '1', label: '非中小' },
      //   { value: '2', label: '中型' }, { value: '3', label: '小型' }, { value: '4', label: '微型' }],
      //   layout: { labelSpan: 7, wrapperSpan: 17 }
      // }, 
      {
        name: "GJLX", label: "规模", type: "select", grid: 6 / 24, required: false, 
        dataType: "number", data: [{ value: '1', label: '大型' },{ value: '2', label: '中型' }, 
        { value: '3', label: '小型' }, { value: '4', label: '微型' }],
        layout: { labelSpan: 7, wrapperSpan: 15 }
      }, {
        name: 'XS', required: false, type: 'button-group',
        data: [{ value: '1', label: '新增', onClick: this.DiviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }],
        grid: 10 / 24, layout: { labelSpan: 7, wrapperSpan: 15 }
      },
    ];
    return (
      <Modal title={this.props.title} okText={"保存"} width={700} visible={this.props.showEdit} onCancel={this.hideEditHandler.bind(this)} onOk={this.diviSubmit.bind(this)} >
        <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
          <div>
            <div className={styles.create}>
              <EditFrom ref="diviForm" daoName={daoName} controls={controlsFilter} clearItemMargin={true} selectFirst={false} />
            </div>
            <DataEditTable ref="table" columns={columns} controls={controls} footer={true} dataSource={list} multiSelect={true}/>
          </div>
        </div>
      </Modal>
    )
  }

}

CompClieQylxWhForm.propTypes = {
  jlid: PropTypes.number,
  showEdit: PropTypes.bool,
  title: PropTypes.string,
  parentModel: PropTypes.string


};
CompClieQylxWhForm.defaultProps = {
  jlid: -1,
  showEdit: false,
  title: "",
  parentModel: ""
};

function mapStateToProps(state) {
  const { list } = state[daoName];
  return {
    list
  }
}
CompClieQylxWhForm = connect(mapStateToProps)(CompClieQylxWhForm)
export default CompClieQylxWhForm;
